using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
using System.Xml;
using System.ComponentModel;
using System.Web.UI;

namespace ARF.Web.Controls
{
    [ToolboxData("<{0}:ListXml runat=\"server\" />"), ToolboxItemFilter("ARF")]
    public class ListXml : XmlProvider, IDisposable
    {
        private string _listName;
        private string _webUrl;

        private SPWeb _contextWeb = null;

        public string WebUrl
        {
            get { return _webUrl; }
            set { _webUrl = value; }
        }

        public string ListName
        {
            get { return _listName; }
            set { _listName = value; }
        }

        protected override void BuildXml()
        {
            try
            {
                XmlAsObject = Utility.Utility.CleanXml(ContextList.Items.Xml);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);

                XmlDocument oError = new XmlDocument();
                oError.LoadXml(string.Format("<Error>{0}</Error>", ex.Message));
                XmlAsObject = oError;
            }
        }

        protected SPList ContextList
        {
            get
            {
                return ListWeb.Lists[ListName];
            }
        }

        protected SPWeb ListWeb
        {
            get
            {
                if (_contextWeb != null) return _contextWeb;

                if (string.IsNullOrEmpty(WebUrl))
                    return Web;

                if (WebUrl == "/")
                    return SPContext.Current.Site.RootWeb;

                return SPContext.Current.Site.OpenWeb(WebUrl);
            }
        }

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            if (_contextWeb != null)
            {
                _contextWeb.Dispose();
                _contextWeb = null;
            }
        }

        #endregion
    }
}
